/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mingq
 */
public class ClientServer extends Thread {

    private ServerSocket ownSerSock;
    private static final String OWN_SERVER = NetTools.getIP();
    private DataInputStream connectedUserReader;
    private DataOutputStream connectedUserWriter;
    private Socket connectedSock;
    private static final int USER_PORT = 8301;
    private static int mPort;
    private ChatBox mChatBox;
    private ChatMain mChatMain;
    private StringBuilder sb;

    public void echo(String str) {
        System.out.println(String.format("Server Port: %s | msg: %s", mPort, str));
    }

    public void setChatMain(ChatMain chatMain) {
        mChatMain = chatMain;
    }

    public void setChatBox(ChatBox chatBox) {
        mChatBox = chatBox;
    }

    public DataInputStream getReader() {
        return connectedUserReader;
    }

    public DataOutputStream getWriter() {
        return connectedUserWriter;
    }

    public static int getPort() {
        return mPort;
    }

    public String getSavedStrings() {
        String str = sb.toString();
        sb.delete(0, sb.length());
        return str;
    }

    public ClientServer(ChatMain chatMain) {
        mChatMain = chatMain;
        sb = new StringBuilder();
        try {
            int port = USER_PORT;
            while (!NetTools.isPortUsed(port)) {
                port += 1;
            }
            ownSerSock = new ServerSocket(port, 10, InetAddress.getByName(OWN_SERVER));
            mPort = port;
        } catch (IOException ex) {
            LogManager.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void initOwnServerSocket() throws IOException {
        connectedSock = ownSerSock.accept();
        OutputStream s = connectedSock.getOutputStream();
        connectedUserWriter = new DataOutputStream(s);
        InputStream is = connectedSock.getInputStream();
        connectedUserReader = new DataInputStream(is);
    }

    public void confrimSendFile() {
        try {
            connectedUserWriter.write(Consts.FL_CONFIRM_START);
        } catch (IOException ex) {
            Logger.getLogger(ClientClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                initOwnServerSocket();
                int msg = -1;
                while ((msg = connectedUserReader.read()) != -1) {
                    switch (msg) {
                        case Consts.MSG_START: {
                            String uid = connectedUserReader.readUTF();
                            String str = connectedUserReader.readUTF();
                            echo(uid);
                            echo(str);
                            if (mChatBox == null && mChatMain != null) {
                                mChatMain.userMsg(uid, true);
                                sb.append(str);
                                //   sb.append("\n");
                            }
                            if (mChatBox != null) {
                                mChatBox.getMeged(str);
                            }
                            echo(str);
                            break;
                        }
                        case Consts.SEND_SHRINK: {
                            String uid = connectedUserReader.readUTF();
                            if (mChatBox == null && mChatMain != null) {
                                mChatMain.userMsg(uid, true);
                                sb.append("给你发了一个震动");
                                sb.append("\n");
                            }
                            if (mChatBox != null) {
                                mChatBox.getShrinked();
                            }
                            break;
                        }
                        case Consts.FL_SEND: {
                            mChatBox.getFiled();
                            break;
                        }
                        case Consts.Fl_START: {
                            String filenames = connectedUserReader.readUTF();
                            int bufferSize = 8192;
                            byte[] buf = new byte[bufferSize];
                            FileOutputStream fos = new FileOutputStream(mChatBox.mSavePath);
                            while (true) {
                                int read = 0;
                                if (connectedUserReader != null) {
                                    read = connectedUserReader.read(buf);
                                }
                                if (read == -1 || buf[0] == Consts.FL_COMPELETE || buf[0] == -1) {
                                    break;
                                }
                                fos.write(buf, 0, read);
                            }
                            fos.close();
                            mChatBox.fileSendSuccessed();
                            break;
                        }
                        default:
                            break;
                    }
                }
            } catch (IOException ex) {
                LogManager.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
